<template>
	<div style="width: 32%; border: green 1px solid">
		<h2 style="text-align: center;">修改/添加</h2>
		编号：<input type="text" v-model="tea.uid" readonly="readonly" /><br>
		名字：<input type="text" v-model="tea.uname" /><br>
		账号：<input type="text" v-model="tea.phone" /><br>
		密码：<input type="text" v-model="tea.pwd" /><br>
		图片：<input type="file" ref="img" /><br>
		<div v-if="tea.uid > 0" style="width: 10vw; height: 10vw">
			<img :src="$ip + `/api/public/showimg/` + tea.pic" style="width: 100%; height: 100%" />
		</div>
		<button @click="addup()">添加/修改</button>
		{{ doadd }}
	</div>
</template>

<script>
export default {
	data() {
		return {
			tea: { uid: 0, uname: '', phone: '', pwd: '', pic: '' },// 初始化教师对象
			token: '',// 令牌
			doadd: ''// 添加或修改结果
		}
	},
	methods: {
		addup() {
			// 判断输入数据是否为空
			if (!this.tea.uname || !this.tea.phone || !this.tea.pwd) {
				alert("添加不允许为空")
				return;
			}

			let path =// 根据uid判断是添加还是修改
				this.tea.uid === 0 ? `${this.$ip}/api/adm/tea/add` : `${this.$ip}/api/adm/tea/update`
			console.log(path)

			const formData = new FormData()
			formData.append("uid", this.tea.uid)
			formData.append("uname", this.tea.uname)
			formData.append("phone", this.tea.phone)
			formData.append("pwd", this.tea.pwd)

			const file = this.$refs.img.files[0]// 获取上传文件
			if (file) {
				formData.append("mypic", file)// 添加文件
			}

			this.$axios.post(path, formData, { headers: { 'Authorization': this.token } })
				.then((resp) => {
					this.doadd = resp.data.msg
					this.$router.push("/adm/teashow")
					console.log(resp.data)
				})
				.catch((error) => {
					console.error('添加/修改教师:', error)
					alert('操作失败')
				})
		}
	},
	mounted() {
		const id = parseInt(this.$route.query.id, 10)// 获取路由参数
		console.log(id)
		this.token = window.localStorage.getItem("token")

		if (id > 0) {
			this.$axios.get(`${this.$ip}/api/adm/tea/findById/${id}`, { headers: { 'Authorization': this.token } })
				.then((resp) => {
					this.tea = resp.data.data
					console.log(resp.data.data)
				})
				.catch((error) => {
					console.error('获取教师信息:', error)
					alert('获取教师信息失败')
				})
		} else {//否则创建一个空的教师对象
			this.tea = { uid: 0, uname: '', phone: '', pwd: '', pic: '' }
		}
	}
}
</script>

<style></style>